export default {
  queryStringToJSON,
  objectToQueryString,
};

function queryStringToJSON(qs) {
  qs = qs || location.search.slice(1);

  let pairs = qs.split("&");
  let result = {};
  pairs.forEach(function (p) {
    let pair = p.split("=");
    let key = pair[0];
    let value = decodeURIComponent(pair[1] || "");

    if (result[key]) {
      if (Object.prototype.toString.call(result[key]) === "[object Array]") {
        result[key].push(value);
      } else {
        result[key] = [result[key], value];
      }
    } else {
      result[key] = value;
    }
  });

  return JSON.parse(JSON.stringify(result));
}

/**
 * @param {JSON} queryObject 查询字段
 * @return {String} 格式化后的 query 字符串 ?k=v
 */
function objectToQueryString(queryObject) {
  let queryString = "";
  for (const key in queryObject) {
    const rawValue = queryObject[key];
    if (rawValue !== undefined && rawValue !== null) {
      let value = null;
      value = rawValue;
      if (typeof rawValue === "boolean") {
        value = Number(rawValue);
      }
      queryString += `&${key}=${value}`;
    }
  }

  if (queryString.length > 0) queryString = `?${queryString.slice(1)}`;
  return queryString;
}
